import { Express, Response, Request } from "express";
import { readblogUser, saveblogUser, readLoiginData } from "../model/blogUser";
import { blog_User } from "../tool/varType";
import { tokenKey } from "../config/config";
const jwt = require("jsonwebtoken");
export default function (app: Express) {
  app.post(
    "/api/registerbloguser",
    async function (req: Request, res: Response) {
      const { email } = req.body;
      //   const data: blog_User = req.body;
      const { success, data } = await readblogUser(email);
      console.log(data, success);
      if (success && data.length != 0) {
        res.json({ success: false, msg: "该邮箱已经被注册" });
      } else {
        const blog_User: blog_User = req.body;
        const { success, data } = await saveblogUser(blog_User);
        if (success) {
          res.json({ success: true, msg: "注册成功" });
        } else {
          res.json({ success: false, msg: "注册失败" });
        }
      }
    }
  );
  app.post("/api/loginblogUser", async function (req: Request, res: Response) {
    const blog_User: blog_User = req.body;
    const { success, data } = await readLoiginData(blog_User);
    console.log(data, success);
    if (!success) {
      res.json({ success: false, msg: "用户名或密码错误" });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: "用户名或密码错误" });
      return;
    }
    /**
     * 获取token
     * jwt.sign({对象},密钥,有效期)
     */
    const token = jwt.sign({ id: data[0].id }, tokenKey, {
      expiresIn: 24 * 60 * 60,
    });
    res.json({ success: true, token: token, data: data });
  });
}
